package cn.login;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import cn.dbconnection.DBConnection;
import cn.dbconnection.MD5Crypt;
import cn.util.Datetime;

public class CreateUser extends Thread {

	Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rst = null;

	public CreateUser() {
		conn = DBConnection.getConnection();
	}

	public int create(String userName, String password) {
		String sql = "SELECT count(*) FROM daim_member WHERE rtrim(username)= ? ;";

		try {
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, userName);
			pstmt.executeQuery();
			rst = pstmt.getResultSet();
			rst.next();
			if (rst.getInt(1) > 0) {// user name has been used
				return 2;
			} else {
				String nowDate = Datetime.getNowDatetime();
				String dbPassword = MD5Crypt.crypt(password);
				sql = "INSERT INTO daim_member (username,pass,createdate,preaccount) VALUES(?,?,?,?)";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, userName);
				pstmt.setString(2, dbPassword);
				pstmt.setString(3, nowDate);
				pstmt.setString(4, nowDate);
				pstmt.execute();
			}
		} catch (SQLException e) {
			e.printStackTrace();
			return 2;
		} finally {
			try {
				if (rst != null) {
					rst.close();
				}
				if (pstmt != null) {
					pstmt.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return 1;
	}
}
